/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */

package opensocial.apps.common.persistence;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

public class DAOService<T> implements PersistenceService<T> {
  private static EntityManagerFactory emf;
  private Class<T> entityClass;
  private static EntityManager entityManager;
  private static final String DEFAULT_PERSIST_UNIT = "default";
  private static String persist_unit;

  public DAOService(Class clazz) {
    if (persist_unit == null) {
      emf = Persistence.createEntityManagerFactory(DEFAULT_PERSIST_UNIT);
    } else {
      emf = Persistence.createEntityManagerFactory(persist_unit);
    }
    entityClass = clazz;
    entityManager = emf.createEntityManager();
  }

  public static void setPersistUnit(String persistunit) {
    persist_unit = persistunit;
  }

  public EntityManager getEntityManager() {
    return entityManager;
  }

  public void save(T object) {
    entityManager.getTransaction().begin();
    entityManager.merge(object);
    entityManager.getTransaction().commit();
  }

  public T find(Object pk) {
    T p = entityManager.find(entityClass, pk);
    return p;
  }

  public List<T> query(String query) {
    return query(query, null);
  }

  public void remove(T obj) {
    entityManager.getTransaction().begin();
    T managed = entityManager.merge(obj);
    entityManager.remove(managed);
    entityManager.getTransaction().commit();
  }

  public List<T> query(String query, Map<String, Object> params) {
    Query q = entityManager.createQuery(query);
    if (params != null)
      for (Entry<String, Object> entry : params.entrySet()) {
        q.setParameter(entry.getKey(), entry.getValue());
      }
    return q.getResultList();
  }

  public T queryFirst(String query, Map<String, Object> params) {
    Query q = entityManager.createQuery(query);
    if (params != null)
      for (Entry<String, Object> entry : params.entrySet()) {
        q.setParameter(entry.getKey(), entry.getValue());
      }
    if (q.getResultList().size() > 0) {
      return (T) q.getResultList().get(0);
    } else {
      return null;
    }
  }

  public int update(String query) {
    entityManager.getTransaction().begin();
    Query q = entityManager.createQuery(query);
    int count = q.executeUpdate();
    entityManager.getTransaction().commit();

    return count;
  }

  public List<T> query(String query, Map<String, Object> params, int first,
      int max) {
    Query q = entityManager.createQuery(query);
    if (params != null)
      for (Entry<String, Object> entry : params.entrySet()) {
        q.setParameter(entry.getKey(), entry.getValue());
      }
    q.setFirstResult(first);
    q.setMaxResults(max);
    return q.getResultList();
  }
}
